using System;
using System.Collections;
using System.Collections.Generic;
using LiteNetLib;
using UnityEngine;
using UnityEngine.UI;

public class LogUI : MonoBehaviour, INetLogger
{
    [SerializeField] private RectTransform LogContent;
    [SerializeField] private Scrollbar LogScr;
    [SerializeField] private Text LogStr;

    private void Start()
    {
        NetDebug.Logger = this;
    }

    private void AddLog(string strLog)
    {
        var tmp = Instantiate(LogStr);
        tmp.transform.SetParent(LogContent, false);
        tmp.text = strLog;
        tmp.gameObject.SetActive(true);
        Debug.Log(strLog);
    }
    
    private object Lock = new object();
    private List<string> LstLog = new List<string>();
    private bool Delay = false;
    private void Update()
    {
        if (Delay)
        {
            LogScr.value = 0;
            Delay = false;
        }
        
        lock (Lock)
        {
            foreach (var log in LstLog)
            {
                AddLog(log);
            }

            Delay = LstLog.Count > 0;
            LstLog.Clear();
        }
    }

    public void WriteNet(NetLogLevel level, string str, params object[] args)
    {
        lock (Lock)
        {
            LstLog.Add($"[{DateTime.Now:HH:mm:ss:fff}]{string.Format(str, args)}");
        }
    }
}
